//
//  Store.swift
//  PokeMaster
//
//  Created by 李腾芳 on 2022/1/11.
//  Copyright © 2022 OneV's Den. All rights reserved.
//

import Foundation
import Combine
import SwiftUI
class Store: ObservableObject {
    @Published var appState = AppState()
    var disposeBag = DisposeBag()
    init() {
        addObserver()
    }
    
    func addObserver() {
        appState.settings.accountChecker.emailIsValid
            .print()
            .sink { isValid in
                self.dispatch(AppAction.settings(.emailValid(isValid)))
        }
        .addToDisposeBag(disposeBag)
        
        appState.settings.accountChecker.registerButtonEnable
            .print()
            .sink { isValid in
                self.dispatch(AppAction.settings(.registerEnable(isValid)))
            }
            .addToDisposeBag(disposeBag)
    }
    func dispatch(_ action: AppAction) {
        let result = AppState.reduce(action: action, state: appState)
        appState = result.0
        if let command = result.1 {
            disposeBag.add(command.execute(in: self))
        }
    }
}
